/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitcan.htm
 *
 * gitcan is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitcan.action.issue;

import java.sql.Timestamp;

import org.zhiqim.gitcan.GitcanConstants;
import org.zhiqim.gitcan.GitIssueSequence;
import org.zhiqim.gitcan.dao.GitModuleDao;
import org.zhiqim.gitcan.dbo.GitBug;
import org.zhiqim.gitcan.dbo.GitBugEx;
import org.zhiqim.gitcan.dbo.GitIssue;
import org.zhiqim.gitsolo.dao.GitMemberDao;
import org.zhiqim.gitsolo.dao.GitProjectDao;
import org.zhiqim.gitsolo.dbo.GitProject;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.StdSwitchAction;
import org.zhiqim.httpd.validate.ones.IsIntegerValue;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.httpd.validate.onex.IsInteger;
import org.zhiqim.kernel.annotation.AnTransaction;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.kernel.util.codes.Base64;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.ZView;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

/**
 * 项目BUG管理，包括列表、详情，增删改
 *
 * @version v1.0.0 @author duanxiaohui 2017-10-19 新建与整理
 */
public class BugAction extends StdSwitchAction implements GitcanConstants
{
    @Override
    protected void validateId(HttpRequest request)
    {
        request.addValidate(new IsNotEmpty("issueId", "请选择一个选项"));
    }

    @Override
    protected void validateForm(HttpRequest request)
    {
        request.addValidate(new IsLen("issueName", "BUG名称不能为空且不能超过50个字符", 1, 50));
        request.addValidate(new IsInteger("moduleId", "请选择BUG所属模块，没有模块请先新建"));
        request.addValidate(new IsIntegerValue("issuePriority", "请选择BUG紧急程度", 1, 3));
        request.addValidate(new IsIntegerValue("bugLevel", "请选择BUG严重程度", 1, 3));
    }

    protected void item(HttpRequest request) throws Exception
    {
        long issueId = request.getParameterLong("issueId");
        GitBugEx item = ORM.get(ZView.class, request).item(GitBugEx.class, new Selector("issueId", issueId));
        if (item == null)
        {
            request.returnCloseDialog("该BUG不存在或数据不完整!");
            return;
        }

        request.setAttribute("item", item);
    }
    
    @Override
    protected void list(HttpRequest request) throws Exception
    {
        int page = request.getParameterInt("page", 1);
        int pageSize = request.getContextAttributeInt("zmr_page_size", 20);
        
        Selector selector = new Selector();
        selector.addMust("projectId", GitProjectDao.getProjectId(request));
        selector.addMaybeLike("issueName", request.getParameter("issueName"));
        selector.addMaybe("issueStatus", request.getParameter("issueStatus"));
        selector.addOrderbyDesc("issueSeq");
        
        String author = request.getParameter("author");
        if (CREATOR.equals(author))
            selector.addMaybe("issueCreator", request.getSessionName());
        else if (MANAGER.equals(author))
            selector.addMaybe("issueManager", request.getSessionName());
        
        PageResult<GitBugEx> result = ORM.get(ZView.class, request).page(GitBugEx.class, page, pageSize, selector);
        result.addConditionMap(request.getParameterMap());
        
        request.setAttribute("memberList", GitMemberDao.listx(request));
        request.setAttribute("result", result); 
    }

    @Override
    protected void add(HttpRequest request) throws Exception
    {
        request.setAttribute("moduleList", GitModuleDao.list(request));
    }
    
    @Override
    protected void modify(HttpRequest request) throws Exception
    {
        long issueId = request.getParameterLong("issueId");
        GitBugEx item = ORM.get(ZView.class, request).item(GitBugEx.class, new Selector("issueId", issueId));
        if (item == null)
        {
            request.returnHistory("该BUG不存在或数据不完整!");
            return;
        }
        
        request.setAttribute("item", item);
        request.setAttribute("moduleList", GitModuleDao.list(request));
    }

    @Override
    @AnTransaction
    protected void insert(HttpRequest request) throws Exception
    {
        long projectId = GitProjectDao.getProjectId(request);
        GitProject project = ORM.get(ZTable.class, request).item(GitProject.class, projectId);
        
        byte[] imageData = null;
        String bugImage = request.getParameterNoFileterOnCNT("bugImage");
        if (Validates.isNotEmpty(bugImage))
        {//粘贴的图片
            int idx = bugImage.indexOf(",");
            imageData = Base64.decode(bugImage.substring(idx+1));
        }
        long moduleId = request.getParameterLong("moduleId");
        String issueName = request.getParameter("issueName");
        String issueDesc = request.getParameterNoFileterOnCNT("issueDesc");
        int issuePriority = request.getParameterInt("issuePriority");
        int bugLevel = request.getParameterInt("bugLevel");
        Timestamp dateTime = Sqls.nowTimestamp();

        GitIssue issue = new GitIssue();
        issue.setIssueId(Ids.longId());
        issue.setProjectId(projectId);
        issue.setIssueName(issueName);
        issue.setIssueType(TYPE_BUG);
        issue.setIssueStatus(CREATED);
        issue.setIssueSeq(GitIssueSequence.nextId(request, projectId));
        issue.setIssuePriority(issuePriority);
        issue.setIssueManager(project.getProjectManager());
        issue.setIssueCreator(request.getSessionName());
        issue.setIssueDesc(issueDesc);
        issue.setIssueCreated(dateTime);
        issue.setIssueModified(dateTime);
        
        ORM.get(ZTable.class, request).insert(issue);
        
        GitBug bug = request.getParameter(GitBug.class);
        bug.setIssueId(issue.getIssueId());
        bug.setModuleId(moduleId);
        bug.setBugLevel(bugLevel);
        bug.setBugImage(imageData);
        
        ORM.get(ZTable.class, request).insert(bug);
        
        GitMemberDao.report(request, request.getSessionName(), projectId, "", "提交了BUG", issue.getIssueSeq());
    }

    @Override
    @AnTransaction
    protected void update(HttpRequest request) throws Exception
    {
        long issueId = request.getParameterLong("issueId");
        GitIssue issue = ORM.get(ZTable.class, request).item(GitIssue.class, issueId);
        if (issue == null)
        {
            request.returnHistory("该项目BUG不存在，请重新选择");
            return;
        }
        
        Updater updater1 = new Updater();
        updater1.addMust("issueId", issueId);
        updater1.addField("issueName", request.getParameter("issueName"));
        updater1.addField("issuePriority", request.getParameterInt("issuePriority"));
        updater1.addField("issueCause", request.getParameterNoFileterOnCNT("issueCause"));
        updater1.addField("issueSolution", request.getParameterNoFileterOnCNT("issueSolution"));
        updater1.addField("issueDesc", request.getParameterNoFileterOnCNT("issueDesc"));

        ORM.get(ZTable.class, request).update(GitIssue.class, updater1);
        
        byte[] imageData = null;
        String bugImage = request.getParameterNoFileterOnCNT("bugImage");
        if (Validates.isNotEmpty(bugImage))
        {//粘贴的图片
            int idx = bugImage.indexOf(",");
            imageData = Base64.decode(bugImage.substring(idx+1));
        }
        
        Updater updater = new Updater();
        updater.addMust("issueId", issueId);
        updater.addField("moduleId", request.getParameterLong("moduleId"));
        updater.addField("bugLevel", request.getParameterInt("bugLevel"));
        if (imageData != null)
            updater.addField("bugImage", imageData);
        
        ORM.get(ZTable.class, request).update(GitBug.class, updater);
        
        GitMemberDao.report(request, request.getSessionName(), GitProjectDao.getProjectId(request), "", "修改了BUG", issue.getIssueSeq());
    }

    @Override
    @AnTransaction
    protected void delete(HttpRequest request) throws Exception
    {
        long issueId = request.getParameterLong("issueId");
        GitIssue issue = ORM.get(ZTable.class, request).item(GitIssue.class, issueId);
        if (issue == null)
        {
            request.returnHistory("该项目BUG不存在，请重新选择");
            return;
        }
        
        ORM.get(ZTable.class, request).delete(GitIssue.class, issueId);
        ORM.get(ZTable.class, request).delete(GitBug.class, issueId);
        
        GitMemberDao.report(request, request.getSessionName(), GitProjectDao.getProjectId(request), "", "删除了BUG", issue.getIssueSeq());
    }
}
